<?php

namespace App\Http\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Http\Requests\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['show']);
    }

    //显示用户个人信息页面
    public function show(User $user)
    {
        return view('users.show', compact('user'));
    }

    //显示编辑个人资料页面
    public function edit(User $user)
    {
        $this->authorize('update',$user);
        return view('users.edit', compact('user'));
    }

    //处理 edit 页面提交的更改
    public function update(UserRequest $userRequest, ImageUploadHandler $uploadHandler, User $user)
    {
        $this->authorize('update',$user);
        $data = $userRequest->all();

        if ($userRequest->avatar) {
            $result = $uploadHandler->save($userRequest->avatar, 'avatars', $user->id, 416);
            if ($result) {
                $data['avatar'] = $result['path'];
            }
        }

        $user->update($data);
        return redirect()->route('users.show', $user->id)->with('success', '个人资料更新成功！');
    }
}
